package message;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.function.Function;

public class StructMessageParserSupplier implements MessageParserSupplier{
	protected ArrayList<Function<? super Object, ? extends MessageParser>> subParsers;
	public StructMessageParserSupplier(ArrayList<Function<? super Object, ? extends MessageParser>> subParsers) {
		this.subParsers = subParsers;
	}
	@Override
	public MessageParser parse(final Object obj) {
		return new AbstractMessageParser(obj) {
			private int iter;
			private int len = subParsers.size();
			private MessageParser[] parsers;
			{
				parsers = new MessageParser[len];
				for(int i = 0; i<len; i++) {
					parsers[i] = subParsers.get(i).apply(object);
				}
			}
			@Override
			public boolean write(ByteBuffer byteBuffer) {
				while(iter < len) {
					if(!(parsers[iter].write(byteBuffer))) return false;
					iter++;
				}
				iter = 0;
				return true;
			}
		};
	}

}
